﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace JESAI.ClamAV.NetScanner.Test
{
    public class IntegrationTestContext
    {
        public HttpContext HttpContext { get; private set; }
        private static object syncRoot = new object();
        internal static IntegrationTestContext testContext;
        public TestServer TestServer { get; private set; }
        public IConfiguration Configuration { get; set; }
        public static IntegrationTestContext CreateDefaultUnitTestContext()
        {
            lock (syncRoot)
            {
                if (testContext == null)
                {
                    testContext = new IntegrationTestContext
                    {
                        HttpContext = new DefaultHttpContext()
                    };

                    string root = AppDomain.CurrentDomain.BaseDirectory;

                    testContext.Configuration = new ConfigurationBuilder()
                        .SetBasePath(root)
                        .AddJsonFile("appsettings.json")
                          .AddJsonFile("hosting.json", optional: true)                     
                        .Build();

                    IWebHostBuilder webHost = new WebHostBuilder()
                        .UseConfiguration(testContext.Configuration)
                        .ConfigureLogging((host, logging) =>
                        {
                            logging.ClearProviders();
                            logging.AddConfiguration(host.Configuration.GetSection("Logging"));                          
                        }).UseStartup<Startup>();

                    testContext.TestServer = new TestServer(webHost);

                    AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
                    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                }

                return testContext;
            }
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is Exception ex)
            {
               
            }
        }

        private static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
        {
            if (e.Exception != null)
            {
               
            }
        }
        /// <summary>
        /// 解析服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T Resolve<T>()
        {
            return TestServer.Host.Services.GetService<T>();
        }
    }
}
